//
//  Status.swift
//  LVWeibo
//
//  Created by lv on 15/6/30.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    
    // MARK:- 数据模型属性
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String? {
        didSet {
            if let result = source?.hrefLink() {
                source = result.text
            }
        }
    }
    /// 配图数组
    var pic_urls: [[String: String]]? {
        didSet {
            
            imageURLs = [NSURL]()
            middleImageURLs = [NSURL]()
            largeImageURLs = [NSURL]()
            
            for dict in pic_urls! {
                // 缩略图
                var urlString = dict["thumbnail_pic"]!
                imageURLs?.append(NSURL(string:urlString)!)
                // 中图
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
                middleImageURLs?.append(NSURL(string: urlString)!)
                // 大图
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                
                largeImageURLs?.append(NSURL(string: urlString)!)
            }
        }
    }
    
    /// 配图URL数组
    var imageURLs: [NSURL]?
    
    /// 计算性属性(若是转发微博返回转发微博的imageURLs,否则返回原创的imageURLs)
    var picURLs: [NSURL]? {
        return retweeted_status == nil ? imageURLs : retweeted_status?.imageURLs
    }
    /// 中图的URL数组
    private var middleImageURLs:[NSURL]?
    var middlePicURLs: [NSURL]? {
        return retweeted_status == nil ? middleImageURLs : retweeted_status?.middleImageURLs
    }
    /// 大图的URL数组
    private var largeImageURLs:[NSURL]?
    var largePicURLs: [NSURL]? {
        return retweeted_status == nil ? largeImageURLs : retweeted_status?.largeImageURLs
    }

    
    /// 用户信息
    var user: User?
    /// 转发微博模型
    var retweeted_status: Status?
    /// 属性数组
    private static let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    
    // MARK:- 字典转模型
    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        super.setValue(value, forKey: key)
        if key == "user" {
            if let userDict = value as? [String: AnyObject] {
                user = User(dict: userDict)            }
            return
        }
        
        if key == "retweeted_status" {
            if let retweetedDict = value as? [String: AnyObject] {
                retweeted_status = Status(dict: retweetedDict)
            }
            return
        }
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    
    // MARK:- 加载微博数据
    class func loadStatuses(since_id: Int,max_id: Int,finished:(result: [Status]?,error: NSError?) -> ()) {
        
        // 发起网络请求
        NetWorkTools.sharedNetWorkTools.loadStatuses(since_id, max_id: max_id) { (array, error) -> () in
            if error != nil {
                finished(result: nil, error: nil)
                return
            }
            if array == nil {
                finished(result: nil, error: nil)
            }
            
            // 将微博字典数组转化为模型数据
            let list = statuses(array!)
            
            // 异步缓存图片
            cacheStatusImages(list, finished: finished)
        }
    }
    
    //MARK:- 缓存微博数组中所有的图片
    private class func cacheStatusImages(statuses: [Status],finished: (result: [Status]?,error: NSError?) ->()) {
        
        // 调度组
        let group = dispatch_group_create()
        
        for s in statuses {
            // 判断配图数组中是否有数据
            if s.picURLs == nil || s.picURLs!.isEmpty{
                continue
            }
            // 遍历URL数组
            for url in s.picURLs! {
                // 进入调度组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    // 离开调度组
                    dispatch_group_leave(group)
                })
            }
        }
        // 图片缓存完成后通知
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            finished(result: statuses, error: nil)
        })
    }
    
    //MARK:- 将字典数组转换成模型数组
    private class func statuses(array:[[String: AnyObject]]) ->[Status] {
        // 定义可变数组
        var arrayM = [Status]()
        
        // 遍历字典数组
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
        return arrayM
    }
    
    //MARK:- 打印对象信息
    override var description: String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
}
